package dice.sinanya.start;

import java.io.File;
import java.io.IOException;

public class Start {
    RunLevel runLevel;
    Config config;
    int serverPort;
    int javaPort;

    public Start(RunLevel runLevel) throws IOException {
        this.config = new Config();
        this.runLevel = runLevel;
        if (needReInputConfig()) {
            config.inputConfig();
        }
        this.serverPort = config.getServerPort();
        this.javaPort = config.getJavaPort();

    }

    public boolean run() throws IOException, InterruptedException {
        if (needReInputConfig()) {
            config.inputConfig();
            this.serverPort = config.getServerPort();
            this.javaPort = config.getJavaPort();
            if (new ListenPort().listenPort(serverPort)) {
                return true;
            } else {
                return startCoolQ();
            }
        } else if (needStartCoolQ()) {
            return startCoolQ();
        }
        return true;
    }

    private boolean startCoolQ() throws IOException, InterruptedException {
        switch (runLevel) {
            case DEBUG:
            case CQA:
                checkCoolQConfig("CQP.cfg");
                new StartCoolQ().start("CQA.exe");
                return coolQStarted();
            case PDEBUG:
            case CQP:
                checkCoolQConfig("CQP.cfg");
                new StartCoolQ().start("CQP.exe");
                return coolQStarted();
            default:
                return false;
        }
    }

    private void checkCoolQConfig(String fileName) throws IOException {
        CoolQConfig coolqConfig = new CoolQConfig();
        File cqx = coolqConfig.findDir(fileName);
        if (!coolqConfig.checkHttpApiOpen(cqx)) {
            throw new IOException("检测到您未开启酷Q中的httpApi插件，请检查");
        }
    }

    private boolean needReInputConfig() throws IOException {
        ListenPort listenPort = new ListenPort();
        return (listenPort.listenPort(serverPort) && listenPort.listenPort(javaPort)) || !new Config().configCantUse();
    }

    private boolean needStartCoolQ() {
        return !new ListenPort().listenPort(serverPort);
    }

    private boolean coolQStarted() throws InterruptedException, IOException {
        ListenPort listenPort = new ListenPort();
        int i = 0;
        while (!listenPort.listenPort(serverPort)) {
            if (i < 20) {
                Thread.sleep(1000);
                i++;
            } else {
                throw new IOException("启动酷Q的httpApi失败，必须于启动exe后30秒内登陆QQ才能正常启动\n如遇到其它问题，请骰主检查或至官方群反馈");
            }
        }
        return true;
    }
}
